﻿using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace TGM
{
    public class ItemConfig
    {
        private List<Item> items = new List<Item>();

        public List<Item> Items
        {
            get { return items; }
            set { items = value; }
        }

        public string GetItemString()
        {
            var builder = new StringBuilder();
            List<Item> list = Items.FindAll(delegate(Item x) { return x.Qty > 0; });
            foreach (Item item in list)
            {
                builder.AppendFormat("{0}_{1},", item.Qty, item.Code);
            }
            return builder.ToString().TrimEnd(new[] {','});
        }

        public static ItemConfig Load()
        {
            if (File.Exists("ItemConfig.xml"))
            {
                var serializer = new XmlSerializer(typeof (ItemConfig));
                var stream = new FileStream("ItemConfig.xml", FileMode.OpenOrCreate);
                try
                {
                    return (ItemConfig) serializer.Deserialize(stream);
                }
                catch
                {
                    return null;
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                    }
                }
            }
            return null;
        }

        public void Save()
        {
            var serializer = new XmlSerializer(typeof (ItemConfig));
            var stream = new FileStream("ItemConfig.xml", FileMode.Create);
            try
            {
                serializer.Serialize(new XmlTextWriter(new StreamWriter(stream)), this);
            }
            catch
            {
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }
        }
    }
}